require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'collection',
    'model',
    'dialog',
    'ztree',
    'calendar'
], function ($, common, ready, template, Collection, Model, dialog) {

    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            loading();
            this.event();
            this.fetch();
        },

        fetch: function (_args) {
            var _this = this;
            var args = _args || {};
            args.limit = 10;
            args.offset = 0;

            _this.collection = new Collection({
                container: 'data-list',
                template: 'data-item',
                url: _global.url.api + 'workers',
                condition: args,
                model: {
                    tag_name: 'tr',
                    event: {},
                    change: function (e) {
                        _this.data[$(e.target).attr('name')] = $(e.target).val();
                    }
                },
                callback: function () {
                    var count = _this.collection.result.child_count;
                    $('#child_count').html('推广员总数：' + count['agency_count'] + '人|下级用户数：' + count['user_count'] + '人|分享家总数：' + count['master_count'] + '人');
                    loaded();
                }
            });
            _this.collection.fetch();

        },

        zTree: function () {
            var setting = {
                async: {
                    enable: true,
                    type: "get",
                    url: _global.url.api + 'workers_childs',
                    autoParam: ["id", "name=n", "level=lv"],
                    otherParam: {
                        "start_time": $('input[name=start_time]').val(),
                        'end_time': $('input[name=end_time]').val()
                    },
                    dataFilter: filter
                },
                callback: {
                    beforeAsync: function (treeId, treeNode) {
                        if (treeNode != undefined) {
                            //获取当前节点的所有父节点,第一个对象即是最顶级的父节点
                            var parent = treeNode.getPath();
                            //获取整个tree的对象
                            var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
                            //如果tree对象不为null,则将顶级节点的id提交到服务端
                            if (treeObj != null) {
                                treeObj.setting.async.otherParam.pid = parent[0].id;

                                var start_time = $('input[name=start_time]').val();

                                if (start_time !== "" && start_time !== undefined && start_time !== null) {
                                    treeObj.setting.async.otherParam.start_time = start_time;
                                }
                                var end_time = $('input[name=end_time]').val();
                                if (end_time !== "" && end_time !== undefined && end_time !== null) {
                                    treeObj.setting.async.otherParam.end_time = end_time;
                                }
                            }
                        }
                    }
                },
                view: {
                    nameIsHTML: true,
                    expandSpeed: "slow"
                }
            };

            function filter(treeId, parentNode, childNodes) {
                if (!childNodes) return null;
                for (var i = 0, l = childNodes.length; i < l; i++) {
                    childNodes[i].name = childNodes[i].name.replace(/\.n/g, '.');
                }
                return childNodes;
            }

            $(document).ready(function () {
                $.fn.zTree.init($("#treeDemo"), setting);
            });
        },

        event: function () {
            var _this = this;
            $('.form_datetime').calendar();
            /**
             * 搜索事件
             */
            $('#btn-search').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.reload();
            });

            $('#refresh').on('click', function (e) {
                e.preventDefault();
                var start_time = $('input[name=start_time]').val();
                var end_time = $('input[name=end_time]').val();
                $.ajax({
                    url: _global.url.api + 'refresh_agency_count',
                    type: 'put',
                    async: false,
                    data: {start_time: start_time, end_time: end_time},
                    success: function (res) {
                        if (res.code == 0) {
                            var count = res.data;
                            $('#child_count').html('推广员总数：' + count['agency_count'] + '人|下级用户数：' + count['user_count'] + '人|分享家总数：' + count['master_count'] + '人');
                        }
                    }
                })
                ;
            });
            $('#render_tree').on('click', function (e) {
                e.preventDefault();
                _this.zTree();
            });
            $('#btn-add').on('click', function (e) {
                _this.data = {}; ////表单临时变量
                e.preventDefault();
                dialog({
                    title: '添加账户',
                    width: 500,
                    content: template('add-tpl'),
                    ok: function () {
                        if (!new Model({
                                url: _global.url.api + 'worker',
                                data: _this.data,
                                valid_config: {
                                    name: 'required',
                                    mobile: 'required'
                                }
                            }).post()) {
                            return false;
                        }
                        _this.fetch();
                    }, cancel: function () {
                    }
                }).show();
                //绑定表单元素更改事件
                $('input, select, textarea').on('change', function (e) {
                    _this.change(e);
                });
            });
        },

        change: function (e) {
            this.data[$(e.target).attr('name')] = $(e.target).val();
        }

    };

    new index();

});